<script lang="ts" setup>
import { ref } from 'vue'
import type { RoleState } from '@/interfaces/api/role'
import {
  addRoleApi,
  deleteRoleApi,
  selectSelectMenuAllApi,
  updateRoleInfoApi,
  updateRoleMenuApi,
} from '@/api'
import { selectRoleListApi, likeRoleListApi } from '@/api'
import { NButton } from 'naive-ui'
import type { FormItem } from '@/interfaces/components/dataForm'
import { useCreateInput } from '@/hooks/renderHook'
import type { DataFormType, ModalMakeType } from '@/interfaces/components'
import { useCreateAiction } from '@/hooks/tableHooks'
import { AddSharp } from '@vicons/ionicons5'
import store from '@/store'
import useRequest from '@/hooks/requestHooks'

const requestUtils = useRequest()
const modalMakeRef = ref<null | ModalMakeType>(null)
const dataFromRef = ref<null | DataFormType>(null)
const ModalFunction = ref<{ node: 'add' | 'update' | ''; id: number }>({
  node: 'add',
  id: 0,
})

const tableColumn = ref([
  {
    title: '角色名称',
    key: 'roleName',
  },
  {
    title: '说明',
    key: 'explainText',
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'make',
    render(row: RoleState) {
      return useCreateAiction([
        {
          label: '菜单权限分配',
          disabled: ref(false),
          type: 'default',
          onClick() {
            updateMenuRole(row)
          },
        },
        {
          label: '编辑角色信息',
          disabled: ref(false),
          type: 'default',
          onClick() {
            updateRoleInfo(row)
          },
        },
        {
          label: '删除',
          disabled: ref(false),
          type: 'error',
          onClick() {
            deleteRoleInfo(row)
          },
        },
      ])
    },
  },
])
const tableData = ref<RoleState[]>([])
const tableLoding = ref<boolean>(false)

const dataFormOptions: Array<FormItem> = [
  {
    key: 'key',
    label: '角色名称',
    value: ref(''),
    render(formItem) {
      return useCreateInput({
        refState: formItem.value,
        inputPropsOptions: {
          placeholder: '请输入角色名',
        },
      })
    },
  },
]
/**
 * @description: 获取表格的数据
 */
const getTableData = async () => {
  requestUtils.useLoadingRequest({
    loadings: tableLoding,
    axios: selectRoleListApi(),
    state: tableData,
  })
}
getTableData()

const showMenuModal = ref(false)

/**
 * @description: 树的所有数据
 */
const treeData = ref<any>([])

/**
 * @description: 树的多选按钮默认选中的数据
 */
const treeMenuKeys = ref<number[]>([])

/**
 * @description: 获取菜单树的全部数据
 */
const selectTreeData = async () => {
  const res = await selectSelectMenuAllApi()
  treeData.value = Object.values(res.data.data)
}
selectTreeData()

/**
 * @description: 点击 “菜单权限分配” 按钮时，触发的函数
 * @param {row} 表格中本行选择的数据
 */
const updateMenuRole = (row: RoleState) => {
  showMenuModal.value = true
  ModalFunction.value.id = row.id as number
  treeMenuKeys.value = row.menuId?.map((item: any) => parseInt(item)) as number[]
}

/**
 * @description: 点击 “编辑角色信息” 按钮时，触发的函数
 * @param {row} 表格中本行选择的数据
 */
const updateRoleInfo = async (row: RoleState) => {
  ModalFunction.value.id = row.id as number
  ModalFunction.value.node = 'update'
  await modalMakeRef.value?.show()
  dataFromRef.value?.update(row)
}

/**
 * @description: 点击 “删除” 按钮时，触发的函数
 * @param {row} 表格中本行选择的数据
 */
const deleteRoleInfo = (row: RoleState) => {
  store.state.dialog?.warning({
    title: '警告',
    content: '你确定？',
    positiveText: '确定',
    negativeText: '不确定',
    onPositiveClick: async () => {
      await deleteRoleApi({ id: row.id as number })
      getTableData()
    },
  })
}

/**
 * @description: 树的多选按钮状态发生改变时触发的函数
 * @param {number[]} keyArr 树的多选按钮选中的所有值
 */
const treeChanged = (keyArr: number[]) => {
  console.log(keyArr)

  treeMenuKeys.value = keyArr
}

/**
 * @description: 表单组件
 */
const searchForm = ref<DataFormType | null>(null)

/**
 * @description: 根据搜索表单的额数据进行对表格数据的筛选
 */
const searchTableData = async () => {
  if (searchForm.value?.validator()) {
    let params = searchForm.value?.generatorParams()
    await requestUtils.useLoadingRequestOrIsNull<RoleState>({
      axios: likeRoleListApi(params),
      state: tableData,
      loadings: tableLoding,
    })
  }
}

/**
 * @description: 重置表单（清空表单）
 */
const resetSearch = () => {
  searchForm.value?.reset()
}

const modalFormOptions: Array<FormItem> = [
  {
    key: 'roleName',
    label: '角色名称',
    value: ref(''),
    required: true,
    render(formItem) {
      return useCreateInput({
        refState: formItem.value,
        inputPropsOptions: {
          placeholder: '请输入角色名',
        },
      })
    },
  },
  {
    key: 'explainText',
    label: '角色说明',
    value: ref(''),
    required: true,
    render(formItem) {
      return useCreateInput({
        refState: formItem.value,
        inputPropsOptions: {
          placeholder: '请输入角色说明',
        },
      })
    },
  },
]

const operationModal = async () => {
  ModalFunction.value.node = 'add'
  await modalMakeRef.value?.show()
  dataFromRef.value?.reset()
}

const confirm = () => {
  // 获取表单的参数
  let params = dataFromRef.value?.generatorParams()

  if (ModalFunction.value.node === 'update') {
    updateConfirm(params)
  } else if (ModalFunction.value.node === 'add') {
    addConfirm(params)
  }
}

/**
 * @description: 更新事件
 */
const updateConfirm = async (params: any) => {
  // 验证表单
  if (dataFromRef.value?.validator()) {
    params['id'] = ModalFunction.value.id
    await updateRoleInfoApi(params)
    await modalMakeRef.value?.colse()
    getTableData()
  }
}

/**
 * @description: 添加事件
 */
const addConfirm = async (params: any) => {
  // 验证表单
  if (dataFromRef.value?.validator()) {
    await addRoleApi(params)
    await modalMakeRef.value?.colse()
    getTableData()
  }
}

/**
 * @description: 更新角色拥有的菜单
 */
const saveRoleMenu = async () => {
  await updateRoleMenuApi({
    id: ModalFunction.value.id,
    child: treeMenuKeys.value,
  })
  showMenuModal.value = false
  getTableData()
}
</script>

<template lang="pug">
div(class="w-full animate__animated animate__fadeIn animate__delay-0.7s" )
  
  n-card(title="角色管理") 用于管理员对角色的管理，可以分配角色可拥有的菜单等权限
  TableBody()
    template(#header) 
      TableHeader(searchContentHeight="200px" @search="searchTableData" @reset-search="resetSearch")
        template(#searchForm)
          DataForm(ref="searchForm" :form-config="{labelWidth: 80}" :options="dataFormOptions" preset="grid-item")
        template(#rightBtn)
          n-button(size="small" type="info" @click="operationModal") 新增
            template(#icon)
              n-icon
                AddSharp
    template(#body)
      n-data-table(:single-line="false" :columns="tableColumn" :data="tableData" :loading="tableLoding")
n-modal(v-model:show="showMenuModal")
  n-card(title="菜单权限分配" style="width: 600px;")
    n-tree(block-line cascade checkable :data="treeData" key-field="id" label-field="title" @update:checked-keys="treeChanged" :default-checked-keys="treeMenuKeys")
    template(#footer)
     n-button(type="primary" @click="saveRoleMenu") 保存
ModalMake(title="菜单控制台" ref="modalMakeRef" contentHeight="20px" @confirm="confirm")
  DataForm(ref="dataFromRef" :form-config="{}" :options="modalFormOptions")

</template>
